<?php
/*
    process flow when responding to an uploaded project zip file
    - location of uploaded zip file: $loadpath
    - original name of (presumably a zip) file - $filename 
    - directory where unzipped files end up - $project->UploadPath()

*/

    error_reporting(E_ALL);

    $relPath = "./pinc/";
    require_once $relPath."dpinit.php";
    require_once $relPath."dp_main.inc";
    require_once $relPath."unzip_project.php";

    $chktext      = Arg("chktext");
    $submitload   = IsArg("submitload");
    $submitdelete = IsArg("submitdelete");

    global $User;
// -------------------------------------------------------

    $User->IsLoggedIn()
        or RedirectToLogin();

    $projectid = ArgProjectId();
    if(! $projectid) {
        die("No projectid provided.");
    }

    $project   = new DpProject($projectid);
    if(! $project->Exists()) {
        die("Project does not exist. Please create one first.");
    }

    if(! $project->MayBeManagedByActiveUser()) {
        die("Security violation!");
    }

    // load up the project and the uploaded file info

    // add/update pages and other images -----------------------
    if($submitload && !empty($chktext) && is_array($chktext)) {
        $protopages = LoadPages($project);
        SubmitWork($chktext, "load", $project, $protopages);
    } 

    if($submitdelete && !empty($chktext) && is_array($chktext)) {
        $protopages = LoadPages($project);
        SubmitWork($chktext, "delete", $project, $protopages);
    } 

    // process and distribute uploaded files -------------------
    if(count($_FILES) > 0) {
        $protopages = LoadPages($project);
        HandleUpoad($project, $_FILES);
    }
    // reload
    $protopages = LoadPages($project);

    ksort($protopages);

// setup up UI ----------------------------------

    $tbl = new DpTable();
    $tbl->SetClass("dark_border");
    $tbl->SetId("tblpages");
    $tbl->AddCaption(null, 1, "dark_border_bottom");
    $tbl->AddCaption("^Currently in project", 2,
            "dark_border_left dark_border_bottom");
    $tbl->AddCaption("^In upload directory", 6, 
            "dark_border_left dark_border_right dark_border_bottom",
            $project->UploadPath());
    $tbl->AddColumn("^Page<br/>name", null, "saypagename", 
                        "dark_border_left dark_border_right");
    $tbl->AddColumn(">Image<br/>(size)", null, "imgcol");
    $tbl->AddColumn(">Text<br>(size)", null, "textlen",
                        "dark_border_right");
    $tbl->AddColumn(">Image<br>(size)", null, "extimgpvw");
    $tbl->AddColumn(">Text<br>(size)", null, "exttxtlen");
    $tbl->AddColumn("^Encoding", null, "encoding");
    $tbl->AddColumn(chkall(), null, "textcheck");

    $tbl->SetRows($protopages);

    function chkall() {
        return "^<input type='checkbox' id='chkall' name='chkall'
                    onclick='eCheckAll(event)'>"._("All");
    }

// page emission ------------------------------

    $args = array("jsfile"  => "filemaster.js",
                  "cssfile" => "filemaster.css");
    DpHeader("FileMaster - ".$project->Title(), $args);
    $delcaption     = _("Delete selected items");
    $loadcaption    = _("Load selected items");
    $uploadcaption  = _("Browse files to upload");

    echo "
  <div class='pagetitle'> {$project->TitleAuthor()} </div>
  <div id='divwork'>\n";
    echo_upload_form();

    /*
    echo "
    <div id='returnto'>
        ". link_to_project($projectid, "Return to project") ."
    </div>\n";
    */

    if(count($protopages) > 0) {
        echo "
      <div id='divworkform'>
        <form name='workform' id='workform' 
                            method='post' action=''>
          ".link_to_project($projectid, "Return to project")."
          <input type='submit' name='submitload' 
                                value='Load selected'/>
          <input type='submit' name='submitdelete' 
                            value='Delete selected'/>\n";
        $tbl->EchoTable();

        echo link_to_project($projectid, "Return to project")."
          <input type='submit' name='submitload' 
                            value='Load selected'/>
          <input type='submit' name='submitdelete' 
                            value='Delete selected'/>
        </form>
    </div> <!-- div.w100 -->\n";
    }
    echo "
  </div> <!-- divwork -->\n";
    echo "
    </div>
    </div>\n";

    dp_footer();
    exit;

    function echo_upload_form() {
    echo "
<form enctype='multipart/form-data' method='post' action=''
        name='upform' id='upform'>
    Select a zip file: 
    <input type='file' name='projectzipfile' size='50'
            onchange='eFileSelect()'>
    <input type='button' value='Upload file' onclick='eUpClick()'
        name='upbutton' id='upbutton'>
    <span id='uploading'> Uploading....</span>
</form>\n";
    }

    function saypagename($page) {
        /** @var $page DpPage */
        return $page->PageName();
    }


    function imgcol( $page) {
        /** @var $page DpPage */
        if(! $page->Exists() || ! $page->IsImageFile())
            return "--";
        // if(! $page->IsImageFile())
            // return "---";

        return link_to_image($page->ProjectId(),
                            $page->PageName(),
                            $page->ImageFileSize(),
                            true); // new window
    }


    function textlen( $page) {
        /** @var $page DpPage */
        return mb_strlen(trim($page->ActiveText())) == 0
            ? "--"
            : mb_strlen($page->ActiveText());
    }

    function encoding($page) {
        /** @var $page DpProtoPage */
        if(! $page->IsExternalText()) {
            return "";
        }
        return is_utf8($page->ExternalText())
            ? "" : 
            ( is_8859_1($page->ExternalText())
                ? "<span class='red'>will convert to utf8</span>"
                : "unknown encoding" 
            );
    }

    function extimgpvw( $page) {
        /** @var $page DpProtoPage */
        return $page->IsExternalImageFile()
            ? link_to_upload_image($page->ProjectId(),
                                   $page->PageName(),
                                   $page->ExternalImageFileSize())
            : "";
    }

    function textcheck($page) {
        /** @var $page DpProtoPage */
        $pagename = $page->PageName();
        return $page->IsExternalText() 
                                || $page->IsExternalImageFile()
            ? "<input type='checkbox'
                        name='chktext[$pagename]'>\n"
            : "";
    }

    function exttxtlen($page) {
        /** @var $page DpProtoPage */
        if(! $page->IsExternalText())
            return "";
        $text = $page->ExternalText();
        if(! is_utf8($text) && ! is_8859_1($text))
            return "encoding problem";
        return is_utf8($text) ? mb_strlen($text) : strlen($text);
    }

    function exttexthidden($page) {
        /** @var $page DpProtoPage */
        return $page->ExternalText();
    }

// other functions --------------------------------------


    function LoadPages($project) {
        // array to hold pages real and prospective
        /** @var $protopgs DpPage[] */
        /** @var $pgs array */
        /** @var $project DpProject */
        $protopgs = array();
        $pgs = $project->PageRows(true);
        $projectid = $project->ProjectId();

    // pages in the project

        // collect info for pages already loaded
        foreach($pgs as $pg) {
            $pagename = $pg['fileid'];
            $protopgs[$pagename] 
                = new DpProtoPage($projectid, $pagename, $project);
        }

    // pages from files

        // what files are in the project upload directory?
        $loadpath = $project->LoadFilePath();
        $files = glob("$loadpath/*");
        foreach($files as $fname) {
            // dump($fname);
            $f = new DpFile($fname);
            if(! $f->Exists())
                continue;
            $pagename = $f->FileNameBase();
            // dump($pagename);
            
            switch($f->Extension()) {
                case "png":
                case "jpg":
                case "gif":
                    // php reality check
                    if(! $f->IsImageFile())  {
                        dump($f->FilePath()." - invalid image file.");
                        continue;
                    }

                    // add to page list if new
                    if(isset($protopgs[$pagename])) {
                        /** @var $proto DpProtoPage */
                        $proto = $protopgs[$pagename];
                    }
                    else {
                        $proto = $protopgs[$pagename] 
                               = new DpProtoPage($projectid,
                                            $pagename, $project);
                    }

                    $proto->SetExternalImageFile($f);
                break;

                case "txt":
                    /** @var $text string */
//                    $text = file_get_contents($fname);
                    // add to page list if new
                    if(isset($protopgs[$pagename])) {
                        $proto = $protopgs[$pagename];
                    }
                    else {
                        $proto = $protopgs[$pagename] 
                               = new DpProtoPage($projectid,
                                            $pagename, $project);
                    }
                    $proto->SetExternalTextFile($f);
                    break;

                default:
                    $project->LogProjectEvent(PJ_EVT_ADD_FILE, $f->FileName());
                    break;
            }
            assert($protopgs[$pagename]);
        }
        return $protopgs;
    }

    function HandleUpoad($project, $afiles) {
        /** @var $project DpProject  */
        $filename   = $afiles['projectzipfile']['name'];
        $zip_path   = $afiles['projectzipfile']['tmp_name'];
        $loadsize   = $afiles['projectzipfile']['size'];
//        $loadtype   = $afiles['projectzipfile']['type'];
        /** @var $loaderror string */
//        $loaderror  = $afiles['projectzipfile']['error'];
        if ( !file_exists($zip_path) )
            die( "source does not exist: $zip_path" );

        if($loadsize == 0) {
            die("Empty file received.");
        }

        $ext = substr($filename, -4);
        switch($ext)
        {
            default:
            case ".txt":
            case ".png":
            case ".jpg":
                move_uploaded_file($zip_path,
                    build_path($project->UploadPath(), $filename));
                break;

            case ".zip":
                // crack zipfile, put it in $project->UploadPath()
                UnzipProject($zip_path, $project);
                break;

        }
    }

    function SubmitWork($chktext, $todo, $project, $protopages) {
        /** @var $project DpProject */
        // dump($chktext);
        foreach($chktext as $pagename => $val) {
            if(! $pagename || ! isset($protopages[$pagename])) {
                dump("load error--");
                dump("{$project->ProjectId()} $pagename");
                /** @var $pg DpProtoPage */
                foreach( $protopages as $name => $pg) {
                    dump($name);
                    dump($pg->PageName());
                }
                die();
            }
            /** @var $protopage DpProtoPage */
            $protopage = $protopages[$pagename];

            switch($todo) {
                case "load":
                    // dump($protopage->ExternalImageFilePath());
                    // dump($protopage->ExternalImageFileName());
                    $protopage->AddOrReplace();
                    // $path = $protopage->ExternalImageFilePath();
                    // $text = $protopage->ExternalText();
                    // $project->AddOrReplacePage(
                        // $pagename,
                        // $path,
                        // $text);
                    $protopage->DisposeExternalFiles();
                    break;

                case "delete":
                    $protopage->DisposeExternalFiles(); 
                    break;
            }
        }
    }
?>
